package com.genius.app.service.impl;

import com.genius.util.Utils.BeanUtils.BeanLab;
import com.genius.util.Utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.genius.app.bean.App;
import com.genius.app.mapper.AppMapper;
import com.genius.app.service.AppService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.genius.util.ConstPool.RedisConstPool.CACHE_APPLIST_KEY;
import static com.genius.util.ConstPool.RedisConstPool.CACHE_APPLIST_TTL;


@Service
public class AppServiceImpl extends ServiceImpl<AppMapper, App> implements AppService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    AppMapper appMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public App getUserByAppId(String AppId) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_id",AppId);
        App app = appMapper.selectOne(queryWrapper);
        return app;
    }

    @Override
    public List<App> getUserByUsername(String Username) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",Username);
        List<App> appList = appMapper.selectList(queryWrapper);
        return appList;
    }

    @Override
    public List<App> getUserByAppRoot(String AppRoot) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_root",AppRoot);
        List<App> appList = appMapper.selectList(queryWrapper);
        return appList;
    }

    @Override
    public App getUserByAppName(String AppName) {
        QueryWrapper<App> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_name",AppName);
        return appMapper.selectOne(queryWrapper);
    }

    @Override
    public List<App> getAppList(String username) throws JsonProcessingException {
        List<App> appList;
        String key = String.format(CACHE_APPLIST_KEY,username);
        String json = stringRedisTemplate.opsForValue().get(key);
        if(json==null){
            logger.info("{} 缓存未命中",key);
            if((appList = getUserByAppRoot("office"))==null){
                return null;
            }
            String arrJson = BeanLab.beanToJson(appList);
            logger.info("设置缓存 {}:{}",key,arrJson);
            RedisUtil.saveRedis(arrJson,key,CACHE_APPLIST_TTL, TimeUnit.HOURS,stringRedisTemplate);
        }else{
            logger.info("{} 缓存命中",key);
            appList = BeanLab.jsonToArray(App.class,json);
        }
        return appList;
    }

}
